package com.suray.wcs.service.pojo.rgv.rgv.protocol.base;

import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.wcs.service.pojo.Rgv;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.exception.FrameLocationException;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.exception.MessageCompleteException;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.exception.MessageErrorException;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.util.RgvMessageType;
import com.suray.wcs.service.util.WcsUtil;

import java.io.IOException;
import java.util.Arrays;

public abstract class RgvRecMessage extends RgvBaseMessage {
    public RgvRecMessage(Rgv rgv, String clazz) {
        super(rgv, clazz);
    }

    public boolean checkMessage(byte[] recData, RgvMessageType rgvMessageType, Integer sendLife) throws IOException {
        checkMessageComplete(recData, this.getMessageSize());

        if (WcsFuncUtil.combineToWord(recData[recData.length - 3], recData[recData.length - 4]) != calcCrc(recData, recData.length - 4)) {
            LoggerUtil.warn("crc校验错误：" + Arrays.toString(recData), this.getClass());
            throw new IOException("crc校验错误");
        }

        readMessage(recData);

        try {
            if (sendLife != null && getMessageLife().intValue() != sendLife) {
                LoggerUtil.warn("收发生命不一致-->发送：" + sendLife + ", 接收:" + getMessageLife(), this.getClass());
                throw new FrameLocationException("收发生命不一致-->发送：" + sendLife + ", 接收:" + getMessageLife());
            }
        } catch (NullPointerException e) {
            WcsUtil.exceptionLog(e, this.getClass());
        }

        if (getMessageType().intValue() != rgvMessageType.getValue()) {
            LoggerUtil.warn("报文类型错误：" + Arrays.toString(recData), this.getClass());
            throw new FrameLocationException("报文类型错误");
        }

//        LoggerUtil.info("接收数据：" + this.toString(), this.getClass());

        return true;
    }

    private void checkMessageComplete(byte[] recData, int messageSize) {
        if (recData.length < messageSize) {
            throw new MessageCompleteException("接收数据长度：" + recData.length + "，小于报文理论长度：" + messageSize);
        } else if (recData.length > messageSize) {
            throw new MessageErrorException("接收数据长度：" + recData.length + "，大于报文理论长度：" + messageSize);
        }
    }
}
